package com.lzh.chatnote.chat.dao;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.chatnote.chat.domain.entity.Message;
import com.lzh.chatnote.chat.domain.enums.MessageStatusEnum;
import com.lzh.chatnote.chat.domain.vo.request.message.MessagePageReq;
import com.lzh.chatnote.chat.mapper.MessageMapper;
import com.lzh.chatnote.common.domian.vo.response.CursorPageBaseResp;
import com.lzh.chatnote.common.enums.CursorEnum;
import com.lzh.chatnote.common.utils.CursorUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 消息表 服务实现类
 * </p>
 *
 * @author lzh
 * @since 2025-09-25
 */
@Service
public class MessageDao extends ServiceImpl<MessageMapper, Message> {

    public CursorPageBaseResp<Message> queryPageMessage(MessagePageReq messagePageReq, Long lastMsgId, Long blackUserId) {
        return CursorUtils.queryCursorPage(this, messagePageReq, wrapper -> {
            wrapper.eq(Message::getRoomId, messagePageReq.getRoomId());
            wrapper.eq(Message::getStatus, MessageStatusEnum.NORMAL.getStatus());
            wrapper.ne(Message::getFromUid, blackUserId);
            wrapper.le(Objects.nonNull(lastMsgId), Message::getId, lastMsgId);
        }, Message::getId, CursorEnum.DESC);
    }


    public Integer getGapCount(Long roomId, Long newMsgId, Long replyMsgId) {
        //房间内的消息是单调递增的
        return lambdaQuery().eq(Message::getRoomId, roomId).gt(Message::getId, replyMsgId).le(Message::getId, newMsgId).count();
    }
}
